package com.dsiab.manageService.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.dsiab.manageService.common.CommonUtils;
import com.dsiab.manageService.common.ResponseMap;
import com.dsiab.manageService.entity.MusicDto;
import com.dsiab.manageService.jwt.JwtAuthService;
import com.dsiab.manageService.service.AccountService;
import com.dsiab.manageService.service.ToolsService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("tools")
public class ToolsController {

    @Autowired
    AccountService accountService;
    @Autowired
    ToolsService toolsService;
    @Autowired
    CommonUtils commonUtils;

    /**
     * 在线编译
     */
    @PostMapping("/deploy")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ResponseMap deploy(@RequestBody Map map) throws Exception {
        // 获取当前目录
        ApplicationHome ah = new ApplicationHome(JwtAuthService.class);
        String docStorePath = ah.getSource().getParentFile().toString();
        String type = (String) map.get("type");
        if (type.isEmpty()){
            throw new Exception("参数错误");
        }
        String shpath = docStorePath + type; //.sh文件的绝对路径
        Process process = null;
        List<String> processList = new ArrayList<String>();
        try {
            // 修改权限，否则无效
            String chmod = "chmod 777 " + shpath;
            Process proc = Runtime.getRuntime().exec(chmod);
            process = Runtime.getRuntime().exec(shpath);
            process.waitFor();
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                processList.add(line);
            }
            input.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        for (String line : processList) {
            System.out.println(line);
        }
        return ResponseMap.success();
    }

    /**
     * 二维码生成
     */
    @PostMapping("/genereateQrcode")
    public ResponseMap genereateQrcode(@RequestBody Map map){
        String url = (String) map.get("url");
        int width = (int) map.get("width");
        int height = (int) map.get("height");
        Map siteInfo = accountService.getSiteInfo();
        String qrcodeName = "/qrcode/" + UUID.randomUUID().toString() + ".jpg";
        String realPath = (String) siteInfo.get("sourceRealUrl") + qrcodeName;
        String sourceUrl = (String) siteInfo.get("sourceUrl") + qrcodeName;
        // 生成指定url对应的二维码到文件，宽和高都是300像素
        QrCodeUtil.generate(url, width, height, new File(realPath));
        return ResponseMap.success(sourceUrl);
    }

    /**
     * 查询归属地
     * @param ip
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/getAddressFromIp")
    public ResponseMap getAddressFromIp(@RequestParam String ip, HttpServletRequest request) throws Exception {
        String localIp = commonUtils.getIpAddr(request);
        String localIpRegion = toolsService.getAddressFromIp(localIp,true);
        String inputIp = toolsService.getAddressFromIp(ip,true);

        Map map = new HashMap();
        map.put("localIp",localIp);
        map.put("inputIp",inputIp);
        map.put("localIpRegion",localIpRegion);
        return ResponseMap.success(map);
    }

    @GetMapping("/deleteUrl")
    public ResponseMap deleteUrl() throws Exception {
        toolsService.deleteUrl();
        return ResponseMap.success();
    }

    /**
     * 查询小说列表
     * @return
     */
    @PostMapping("/getBookList")
    @PreAuthorize("hasRole('ROLE_author')")
    public ResponseMap getBookList() {
        Map siteInfo = accountService.getSiteInfo();
         String realPath = (String) siteInfo.get("bookUrl");
        //  String realPath = "/Users/wilkwo/Downloads/云产品特惠专区素材";
        // File dir =new File("/data/wwwroot/default/uploadFile");//浏览F盘a文件夹下的所有内容
        File dir =new File(realPath);//浏览F盘a文件夹下的所有内容
        // File dir =new File("/Users/xxn/Downloads/");//浏览F盘a文件夹下的所有内容
        File[] files=dir.listFiles();   //列出所有的子文件
        if (files == null) {
            ArrayList array = new ArrayList();
            return new ResponseMap(0, "暂无数据",array);
        }
        ArrayList arrayList = new ArrayList();
        for(File file :files) {
            if(file.isFile()){
                //如果是文件，则输出文件名字
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("filename", file.getName());
                arrayList.add(itemMap);
            }else if(file.isDirectory()) {
                // 如果是文件夹，则输出文件夹的名字，并递归遍历该文件夹
                // System.out.println(file.getName());
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", arrayList);
        resultMap.put("sourceUrl", (String)siteInfo.get("sourceUrl"));
        return new ResponseMap(0, "查询成功", resultMap);
    }

    /**
     * 查询小说详情
     * @param filename
     * @return
     * @throws IOException
     */
    @GetMapping("/getBookDetail")
    @PreAuthorize("hasRole('ROLE_author')")
    public String getBookDetail(@RequestParam String filename) throws IOException {
        Map siteInfo = accountService.getSiteInfo();
        String realPath = (String) siteInfo.get("bookUrl") + filename;
        File file =new File(realPath);//浏览F盘a文件夹下的所有内容
        if (!file.exists()){
            throw new Error("error");
        }
        InputStreamReader read = new InputStreamReader(new FileInputStream(file),"utf8");//考虑到编码格式
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        String tempTxt = "";
        while((lineTxt = bufferedReader.readLine()) != null){
            //  System.getProperty("line.separator")   为换行符号
            tempTxt+=lineTxt + System.getProperty("line.separator");
        }
        read.close();
        return tempTxt;
    }

    @PostMapping("/getMusicList")
    @PreAuthorize("hasRole('ROLE_author')")
    public ResponseMap getMusicList(@RequestBody MusicDto musicDto) {
        return new ResponseMap(0, "查询成功", toolsService.getMusicList(musicDto.getPageNum(), musicDto.getPageSize()));
    }
    @PostMapping("/insertMusicItem")
    public ResponseMap insertMusicItem(@RequestBody MusicDto musicDto) {
        toolsService.insertMusicItem(musicDto);
        return new ResponseMap(0, "查询成功");
    }
    @PostMapping("/updateMusicItem")
    public ResponseMap updateMusicItem(@RequestBody MusicDto musicDto) {
        toolsService.updateMusicItem(musicDto);
        return new ResponseMap(0, "查询成功");
    }
    @PostMapping("/delMusicItem")
    public ResponseMap delMusicItem(@RequestBody MusicDto musicDto) {
        toolsService.delMusicItem(musicDto.getId());
        return new ResponseMap(0, "查询成功");
    }
}
